﻿using jutehui.BLL;
using jutehui.Model;
using jutehui.GetData;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace GetData
{
    public class haitao55
    {
        /// <summary>
        /// 55海淘 HTML信息 获取商品信息 并保存到数据库
        /// </summary>
        /// <returns></returns>
        public string GetSaleURL(string url)
        {
            var htmlText = CustomMethod.GetHtmlByHttpHelper(url);
            var productList = GetProductByRegexToHtml(htmlText);
            if (productList == null || productList.Count < 1)
            {
                return "网络异常，未能获取数据";
            }
            // GetProductList(jsonStr, productList);//得到要插入数据库的数据
            //保存数据库
            DataTable dt = null;
            //转化成table插入
            string errorMsg = "";
            dt = CustomMethod.ListToDataTable<jutehui.Model.Product>(productList, "Product", ref errorMsg);
            if (dt == null || dt.Rows.Count < 1)
            {
                return errorMsg;
            }
            jutehui.BLL.Product bll = new jutehui.BLL.Product();
            string msg = "";

            if (bll.SaveTableData("Product", dt, out msg))
            {
                return "";
            }
            else //返回失败信息
            {
                CustomMethod.WriteLog("55海淘：" + msg);
                return msg;
            }
        }
        /// <summary>
        /// 根据正则解析商品信息
        /// </summary>
        /// <param name="htmlText"></param>
        /// <returns></returns>
        private List<jutehui.Model.Product> GetProductByRegexToHtml(string htmlText)
        {
            List<jutehui.Model.Product> pList = new List<jutehui.Model.Product>();
            string productRegex = @"<ul class=""index-deal-list"" id='deal_list'>[\s\S]*?</ul>";
            var listContent = CustomMethod.GetInfoByRegex(productRegex, htmlText, 0);
            if (listContent == null || listContent.Count < 1)
            {
                string msg = "55海淘：GetProductByRegex ，没有抓到匹配的商品区域，检查匹配规则。";
                CustomMethod.WriteLog(msg);
                return null;
            }
            productRegex = @"<li>[\s\S]*?</li>";
            var list = CustomMethod.GetInfoByRegex(productRegex, listContent[0], 0);
            if (list == null || list.Count < 1)
            {
                string msg = "55海淘：GetProductByRegex ，没有抓到匹配的商品，检查匹配规则。";
                CustomMethod.WriteLog(msg);
                return null;
            }
            //每个商品匹配所有相关属性并赋值
            for (int index = 0; index < list.Count; index++)
            {
                jutehui.Model.Product product = new jutehui.Model.Product();
                product.FromWeb = "55海淘";
                product.TypeId = (int)MallsEnumClass.NavigationType.海淘;
                try
                {
                    var herList = CustomMethod.GetInfoFroma(list[index]);
                    if (herList == null || herList.Count < 1)
                    {
                        string msg = "55海淘：GetProductByRegex ，没有获取到href信息。";
                        CustomMethod.WriteLog(msg);
                        continue;
                    }
                    string namePrice = herList[1];
                    int startIndex = namePrice.IndexOf("<b>");
                    if (startIndex > 0)
                    {
                        product.Pname = Regex.Replace(namePrice, @"<(.[^>]*)>", "");
                        product.Price = namePrice.Substring(startIndex + 3, namePrice.Length - startIndex - 3).Replace("</b>", "").Replace("<b>", "").Trim();
                    }
                    else
                    {
                        product.Pname = namePrice.Trim();
                    }
                    product.Source = herList[herList.Count - 1];
                    //图片链接
                    string srcRegex = @"data-original=[""|']([^""|']*)[""|']";
                    var srcImg = CustomMethod.GetInfoByRegex(srcRegex, list[index], 1);
                    if (srcImg == null || srcImg.Count < 1)
                    {
                        continue;
                    }
                    product.ImgUrl = srcImg[0].Split('@').ToList()[0];
                    string divRegex = @"<div class=""index-deal-des-wrap clearfix"">[\s\S]*?<div class=""index-deal-des-more clearfix"">";
                    var divContent = CustomMethod.GetInfoByRegex(divRegex, list[index], 0);
                    if (divContent == null || divContent.Count < 1)
                    {
                        string msg = "55海淘：GetProductByRegex ，没有获取商品描述信息，购买地址。";
                        CustomMethod.WriteLog(msg);
                        continue;
                    }
                    string despRegex = @"<p>[\s\S]*?</p>";
                    var desList = CustomMethod.GetInfoByRegex(despRegex, divContent[0], 0);
                    string description = "";
                    if (desList == null || desList.Count < 1)
                    {
                        product.Description = product.Pname;
                    }
                    else
                    {
                        for (int count = 0; count < desList.Count; count++)
                        {
                            description += Regex.Replace(desList[count], @"<(.[^>]*)>", "") + "|||";

                        }
                        product.Description = description;
                    }
                    var urlList = CustomMethod.GetInfoFroma(divContent[0]);
                    if (urlList == null || urlList.Count < 1)
                    {
                        continue;
                    }
                    string productUrl = "";
                    string firsBuyUrl = urlList[0];
                    //判断是否返利
                    string spanRegex = @"<span>[\s\S]*?</span>";
                    var fanliConten = CustomMethod.GetInfoByRegex(spanRegex, list[index], 0);
                    if (fanliConten != null && fanliConten.Count > 0 && fanliConten[0].Trim().Contains("返利"))
                    {
                        string detailText = CustomMethod.GetWebHTML(firsBuyUrl);
                        string logRegext = @"<div class=""go-login-main"">[\s\S]*?</div>";
                        var urlContent = CustomMethod.GetInfoByRegex(logRegext, detailText, 0);
                        if (urlContent == null || urlContent.Count < 1)
                        {
                            string msg = "55海淘：GetProductByRegex ，没有获取商品链接区域内容。返利";
                            CustomMethod.WriteLog(msg);
                            continue;
                        }
                        var buyUrlList = CustomMethod.GetInfoFroma(urlContent[0]);
                        product.Plink = MallsEnumClass.GetSourceUrl(buyUrlList[0], ref productUrl);
                        if (product.Plink == "")
                        {
                            string msg = "55海淘：GetProductByRegex ，没有获取商品链接。返利";
                            CustomMethod.WriteLog(msg);
                            continue;
                        }
                        product.Memo = productUrl;

                    }
                    else
                    {
                        product.Plink = CustomMethod.GetTrueUrl(firsBuyUrl, ref productUrl);
                        if (product.Plink == "")
                        {
                            string msg = "55海淘：GetProductByRegex ，没有获取商品链接。";
                            CustomMethod.WriteLog(msg);
                            continue;
                        }

                    }
                    product.Memo = productUrl;

                }
                catch (Exception ex)
                {
                    CustomMethod.WriteLog("55海淘：" + ex.Message.ToString());
                    continue;
                }
                product.UpdateTime = DateTime.Now;
                product.UpdateTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                product.Pname = product.Pname.Replace("&#x2F;", "/").Replace("#039;", "'").Replace("&amp;", "&").Replace("&#x27;", "'"); ;
                pList.Add(product);
            }

            pList.Reverse();
            return pList;
        }
    }
}
